package com.ming.multifunction.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ming.multifunction.common.ErrorCode;
import com.ming.multifunction.exception.BusinessException;
import com.ming.multifunction.mapper.InterestMapper;
import com.ming.multifunction.model.domain.Interest;

import com.ming.multifunction.model.domain.User;
import com.ming.multifunction.model.request.InterestRequest;
import com.ming.multifunction.model.vo.InterestVO;
import com.ming.multifunction.service.InterestService;
import com.ming.multifunction.service.UserService;
import com.ming.multifunction.utils.Mindistance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiSuiMing
 * @description 针对表【interest(交友帖子表)】的数据库操作Service实现
 * @createDate 2024-03-23 17:28:49
 */
@Service
public class InterestServiceImpl extends ServiceImpl<InterestMapper, Interest>
        implements InterestService {

    @Resource
    private UserService userService;

    @Override
    public long saveInterestPost(InterestRequest interest, User loginUser) {

        if (interest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        long loginUserId = loginUser.getId();
        if (loginUserId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }

        User user = userService.getById(loginUserId);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }

        String description = interest.getDescription();
        if (StringUtils.isBlank(description)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "描述不能为空");
        }

        if (description.length()>150) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "描述长度不能超过150");
        }

        List<String> list = interest.getTags();
        List<String> newList = list.stream().filter(tag -> StringUtils.isNotBlank(tag)).collect(Collectors.toList());

        if (newList.size() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "至少输入一个有效标签");
        }
        if (newList.size() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "有效标签数量不能多于5个");
        }

        String imageUrl = interest.getImageUrl();
        if (StringUtils.isBlank(imageUrl)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片不能为空");
        }
        LambdaQueryWrapper<Interest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(loginUserId > 0, Interest::getUserId, loginUserId);
        long count = this.count(wrapper);
        if (count>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"每个用户只能发布一个卡片！");
        }

        Interest interest1 = new Interest();
        BeanUtils.copyProperties(interest, interest1);
        interest1.setUserId(loginUserId);
        boolean save = this.save(interest1);
        Long interest1Id = interest1.getId();
        if (!save || interest1Id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "发布失败");
        }
        return interest1Id;
    }

    @Override
    public List<InterestVO> matchInterest(User loginUser) {

        long userId = loginUser.getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }

        //查询当前登录用户的发布
        LambdaQueryWrapper<Interest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId > 0, Interest::getUserId, userId);
        Interest interest = this.getOne(wrapper);
        if (interest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请先发布兴趣标签后再开启匹配");
        }

        List<String> personTags = interest.getTags();
        //查询所有标签
        List<Interest> interestList = this.list();
        SortedMap<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i < interestList.size(); i++) {

            Interest interest1 = interestList.get(i);
            List<String> otherTags = interest1.getTags();

            if (CollectionUtils.isEmpty(otherTags) || interest1.getUserId() == userId) {
                continue;
            }
            int distance = Mindistance.minDistance(otherTags, personTags);
            map.put(i, distance);
        }

        Set<Map.Entry<Integer, Integer>> entry2 = map.entrySet();
        //这里将map.entrySet()转换成list
        List<Map.Entry<Integer, Integer>> distanceList = new ArrayList<Map.Entry<Integer, Integer>>(entry2);
        //按value排序
        Collections.sort(distanceList, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }

        });

        int num = 6;
        List<Map.Entry<Integer, Integer>> entryList = distanceList.stream().limit(num).collect(Collectors.toList());
        List<InterestVO> interestVOList = new ArrayList<>();

        for (Map.Entry<Integer, Integer> i : entryList) {
            //根据key值拿到对应的value
            Interest sortedInterest = interestList.get(i.getKey());
            //取出用户id
            long uid = sortedInterest.getUserId();
            //如果用户Id等于登录用户的Id则跳到下一轮遍历
            if (uid == userId) {
                continue;
            }

            InterestVO interestVO = new InterestVO();
            BeanUtils.copyProperties(sortedInterest, interestVO);

            User user = userService.getById(uid);
            //把用户的avatarUrl和username 封装给interestVO返回给前端
            interestVO.setUserAvatar(user.getAvatarUrl());
            interestVO.setUsername(user.getUsername());
            interestVOList.add(interestVO);
        }

        return interestVOList;
    }
}




